package com.common.util;

import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.util.ValidatorUtils;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.Resources;
import org.apache.struts.util.RequestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Locale;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * User: NZhao
 * Date: 2007-8-16
 * Time: 14:53:09
 */
public class ValidationUtil {
    /**
     * Ensures the the current date field is not earlier than the to date
     * field.
     *
     * @param bean    The bean validation is being performed on.
     * @param va      The ValidatorAction that is currently being performed.
     * @param field   The Field object associated with the current field
     *                being validated.
     * @param oErrors The ActionMessages object to add errors to if any
     *                validation errors occur.
     * @param request Current request object.
     * @return true if validation passed
     */
    public static boolean validateFromToDate(Object bean,
                                             ValidatorAction va,
                                             Field field,
                                             ActionMessages oErrors,
                                             HttpServletRequest request) {
        try {
            String sToDate = ValidatorUtils.getValueAsString(bean, field.getProperty());
            String sFromProperty = field.getVarValue("fromDate");
            String sFromDate = ValidatorUtils.getValueAsString(bean,sFromProperty);

            if ((sFromDate == null) || (sToDate == null) || sFromDate.equals("") || sToDate.equals("")) {
                return true;
            }

            Date dtFrom = validateFormatDate(sFromDate, va, field, oErrors,request);
            Date dtTo = validateFormatDate(sToDate, va, field, oErrors, request);
            String sAllowsSameDay = field.getVarValue("allowsSameDay");

            if ((sAllowsSameDay == null) || sAllowsSameDay.equalsIgnoreCase("true")) {
                if (dtFrom.compareTo(dtTo) > 0) {
                    oErrors.add(field.getKey(), Resources.getActionMessage(request,va, field));

                    return false;
                }
            } else if (dtFrom.compareTo(dtTo) >= 0) {
                oErrors.add(field.getKey(), Resources.getActionMessage(request, va,field));
                return false;
            }

            return true;
        }
        catch (Exception e) {
            oErrors.add(field.getKey(), Resources.getActionMessage(request, va,field));
        }

        return false;
    }

    public static Date validateFormatDate(String value,
                                          ValidatorAction va,
                                          Field field,
                                          ActionMessages errors,
                                          HttpServletRequest request) {
        Date result = null;
        String datePattern = field.getVarValue("datePattern");
        String datePatternStrict = field.getVarValue("datePatternStrict");
        Locale locale = RequestUtils.getUserLocale(request, null);

        if (!GenericValidator.isBlankOrNull(value)) {
            try {
                if ((datePattern != null) && (datePattern.length() > 0)) {
                    DateFormat format = new SimpleDateFormat(datePattern, locale);
                    result = format.parse(value);
                } else if ((datePatternStrict != null) && (datePatternStrict.length() > 0)) {
                    DateFormat format = new SimpleDateFormat(datePatternStrict, locale);
                    result = format.parse(value);
                } else {
                    result = DateFormat.getDateInstance().parse(value);
                }
            }
            catch (Exception e) {
                errors.add(field.getKey(), Resources.getActionMessage(request, va,field));
            }

            if (result == null) {
                errors.add(field.getKey(), Resources.getActionMessage(request, va,field));
            }
        }

        return result;
    }
}
